package cn.mothin.service.system;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.mothin.config.SystemConfig;
import cn.mothin.dao.OrganizationDao;
import cn.mothin.dao.OrganizationManagerDao;
import cn.mothin.dao.SystemRoleDao;
import cn.mothin.dao.SystemUserDao;
import cn.mothin.dao.SystemUserRoleDao;
import cn.mothin.entity.Organization;
import cn.mothin.entity.OrganizationManager;
import cn.mothin.entity.SystemRole;
import cn.mothin.entity.SystemUser;
import cn.mothin.entity.SystemUserRole;
import cn.mothin.frame.bean.ActionResult;
import cn.mothin.frame.core.base.BaseService;
import cn.mothin.frame.help.ConfigHelper;
import cn.mothin.frame.help.Password;
import cn.mothin.frame.help.UniqueCode;
import cn.mothin.frame.util.ObjectUtil;
import cn.mothin.frame.util.StringUtil;
import cn.mothin.vo.system.UserForm;

@Service("540029747b0bf81ac00a981a")
public class UserService extends BaseService {
    @Autowired
    private SystemUserDao systemUserDao;
    @Autowired
    private ConfigHelper configHelper;
    @Autowired
    private SystemUserRoleDao systemUserRoleDao;
    @Autowired
    private SystemRoleDao systemRoleDao;
    @Autowired
    private OrganizationManagerDao organizationManagerDao;
    @Autowired
    private OrganizationDao organizationDao;
    
    public String queryUserRole(UserForm userForm){
        return  toJson(systemRoleDao.queryUserRole(userForm.getSystemUser().getId()));
    }

    public String query(UserForm userForm) {
        String sql = "SELECT id, name, sex, account, title,  email, state,organizationId "
                + "FROM SYSTEM_USER WHERE deleted<>TRUE AND superUser = FALSE ";
        return systemUserDao.queryJson(userForm, sql);
    }

    public void queryUser(UserForm userForm) {
        String id = userForm.getSystemUser().getId();
        SystemUser systemUser = this.systemUserDao.get(id);
        ObjectUtil.SyncObjectsWithFields(userForm.getSystemUser(), systemUser,
                "id", "name", "sex", "account", "organizationId", "title",
                "telephone", "mobile", "state", "email", "memo");

    }

    public ActionResult addSystemUser(UserForm userForm) {
        ActionResult result = ActionResult.getInstance();
        SystemUser systemUser = new SystemUser();
        String account = userForm.getSystemUser().getAccount();
        /*
         * 姓名冲突不作为筛选条件 if (findByName(name).size() > 0) { return 1; }
         */
        if (systemUserDao.findSystemUsersByAccount(account).size() > 0) {
            result.setOk(false);
            result.setMessage("此姓名已经存在！");
        }

        String id = UniqueCode.make();
        systemUser.setId(id);
        systemUser.setName(userForm.getSystemUser().getName());
        systemUser.setPassword(Password.encrypt(configHelper.getString(SystemConfig.CONFIG_DEFAULT_PASSWORD.getId())));
        systemUser.setSex(userForm.getSystemUser().getSex());
        systemUser.setAccount(userForm.getSystemUser().getAccount());
        if (StringUtil.isNullOrEmpty(userForm.getSystemUser()
                .getOrganizationId())) {
            systemUser.setOrganizationId(null);
        } else {
            systemUser.setOrganizationId(userForm.getSystemUser()
                    .getOrganizationId());
        }
        systemUser.setTitle(userForm.getSystemUser().getTitle());
        systemUser.setTelephone(userForm.getSystemUser().getTelephone());
        systemUser.setMobile(userForm.getSystemUser().getMobile());
        systemUser.setEmail(userForm.getSystemUser().getEmail());
        systemUser.setMemo(userForm.getSystemUser().getMemo());
        systemUser.setState(userForm.getSystemUser().getState());
        systemUserDao.save(systemUser);

        if (userForm.getRoles() != null && userForm.getRoles().length > 0) {
            saveSystemUserRoles(systemUser, userForm.getRoles());
        } else {
            systemUserRoleDao.removeAll(systemUser.getId());
        }
        // 初始化staff_manager表
        // staffManagerSynchronization.doSynchronization();
        return result;
    }

    public void saveSystemUserRoles(SystemUser systemUser, String[] roles) {
        List<SystemUserRole> list = systemUserRoleDao
                .findSystemUserRoles(systemUser.getId());
        if (list.size() > 0) {
            systemUserRoleDao.delete(list);
        }
        if (roles == null) {
            return;
        }
        List<SystemUserRole> list2 = new ArrayList<SystemUserRole>();
        for (int i = 0; i < roles.length; i++) {
            SystemRole systemRole = systemRoleDao.get(roles[i]);
            if (systemRole == null) {
                continue;
            }

            SystemUserRole systemUserRole = new SystemUserRole();
            systemUserRole.setId(UniqueCode.make());
            systemUserRole.setSystemRoleId(roles[i]);
            systemUserRole.setSystemUserId(systemUser.getId());
            list2.add(systemUserRole);
        }
        if (list2.size() > 0) {
            systemUserRoleDao.save(list2);
        }
    }

    public ActionResult update(UserForm userForm) {
        ActionResult result = ActionResult.getInstance();
        List<SystemUser> accountList = systemUserDao.findByAccountNotId(
                userForm.getSystemUser().getAccount(), userForm.getSystemUser()
                        .getId());
        if (accountList.size() > 0) {
            result.setOk(false);
            result.setMessage("此帐号已存在！");
        }
        SystemUser systemUser = this.systemUserDao.get(userForm.getSystemUser()
                .getId());
        if (systemUser == null) {
            result.setOk(false);
            result.setMessage("当前登录帐号不存在！");
        }
        // 查出用户原本属于的组织机构
        List<String> orgList = systemUserDao.queryOrganization(userForm
                .getSystemUser().getId());
        // 查出原本组织机构的负责人和分管部门
        List<String> managerList = systemUserDao.queryManager(orgList.get(0));
        List<String> orgManagerList = systemUserDao.queryOrgManger(userForm
                .getSystemUser().getId());
        ObjectUtil.SyncObjectsWithFields(systemUser, userForm.getSystemUser(),
                "name", "sex", "account", "title", "telephone", "mobile",
                "email", "memo", "state");
        String orgId = userForm.getSystemUser().getOrganizationId();
        if (StringUtil.isNullOrEmpty(orgId)) {
            systemUser.setOrganizationId(null);
        } else {
            systemUser.setOrganizationId(orgId);
        }

        // 如果原本的组织和改变后的组织不同
        if (orgList.get(0) == null || !orgList.get(0).equals(orgId)) {
            if (orgManagerList != null && orgManagerList.size() > 0) {
                OrganizationManager orgManager = organizationManagerDao
                        .get(orgManagerList.get(0));
                organizationManagerDao.delete(orgManager);
            }
            // 如果之前的部门负责人是当前用户
            if (managerList != null && managerList.size() > 0
                    && managerList.get(0) != null) {
                if (managerList.get(0).equals(userForm.getSystemUser().getId())) {
                    Organization org = organizationDao.get(orgList.get(0));
                    org.setManager(null);
                    organizationDao.update(org);
                }
            }
        }
        systemUserDao.update(systemUser);

        if (userForm.getRoles() != null && userForm.getRoles().length > 0) {
            saveSystemUserRoles(systemUser, userForm.getRoles());
        } else {
            systemUserRoleDao.removeAll(systemUser.getId());
        }
        // 初始化staff_manager表
        // staffManagerSynchronization.doSynchronization();
        // return 0;
        return result;
    }

    public ActionResult delete(UserForm userForm) {
        ActionResult result = ActionResult.getInstance();
        SystemUser systemUser = this.systemUserDao.get(userForm.getSystemUser()
                .getId());
        if (systemUser == null) {
            result.setOk(false);
            result.setMessage("用户不存在");
        } else if (systemUser.isDeleted()) {
            result.setOk(false);
            result.setMessage("用户已不存在");
        }
        systemUser.setDeleted(true);
        systemUserDao.update(systemUser);
        // 初始化staff_manager表
        // staffManagerSynchronization.doSynchronization();
        return result;
    }

    public ActionResult resetpsw(UserForm userForm) {
        ActionResult result = ActionResult.getInstance();
        String id = userForm.getSystemUser().getId();
        SystemUser systemUser = this.systemUserDao.get(id);
        if (systemUser == null) {
            result.setOk(false);
            result.setMessage("用户不存在");
        } else if (systemUser.isDeleted()) {
            result.setOk(false);
            result.setMessage("用户已删除");
        }
        systemUser.setPassword(Password.encrypt(configHelper.getString(SystemConfig.CONFIG_DEFAULT_PASSWORD.getId())));
        systemUserDao.update(systemUser);
        return result;
    }
    
    public ActionResult saveState(UserForm userForm){
        ActionResult result = ActionResult.getInstance();
        String id = userForm.getSystemUser().getId();
        SystemUser systemUser = this.systemUserDao.get(id);
        if (systemUser == null) {
            result.setOk(false);
            result.setMessage("用户不存在");
        } else if (systemUser.isDeleted()) {
            result.setOk(false);
            result.setMessage("用户已删除");
        }
        systemUser.setState(userForm.getSystemUser().getState());
        systemUserDao.update(systemUser);
        return result;
    }
}
